package jp.co.piratealliance.pirateAllianceWeb.helper;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;

import org.jivesoftware.smack.AccountManager;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smackx.vcardtemp.packet.VCard;

/**
 * copyright pirate alliance team 2014
 *
 * @author xuwei
 *
 */
public class XMPPHelper
{
	/**
	 * 默认端口
	 */
	public static final int XMPP_PORT = 5222;

	/**
	 * XMPP连接取得
	 *
	 * @param domain
	 * @return
	 * @throws XMPPException
	 */
	public static XMPPConnection getConnection(String domain)
			throws XMPPException
	{
		return getConnection(domain, XMPP_PORT);
	}

	/**
	 * XMPP连接取得
	 *
	 * @param domain
	 * @param port
	 * @return
	 * @throws XMPPException
	 */
	public static XMPPConnection getConnection(String domain, int port)
			throws XMPPException
	{
		// 连接参数
		ConnectionConfiguration connConfig = new ConnectionConfiguration(
				domain, port);
		connConfig.setReconnectionAllowed(true);
		connConfig.setSecurityMode(SecurityMode.disabled); // SecurityMode.required/disabled
		connConfig.setCompressionEnabled(false);
		// 设置是否在登陆的时候告诉服务器，默认为true
		connConfig.setSendPresence(false);

		XMPPConnection connection = new XMPPTCPConnection(connConfig);

		return connection;
	}

	/**
	 * 注册用户
	 *
	 * @param connection
	 * @param username
	 * @param password
	 * @return
	 */
	public static boolean createAccount(XMPPConnection connection,
			String username, String password, Map<String, String> attributes)
	{
		try
		{
			AccountManager.getInstance(connection).createAccount(username,
					password, attributes);

			return true;
		}
		catch (Exception e)
		{
			return false;
		}
	}

	/**
	 * 删除当前用户
	 *
	 * @param connection
	 * @return
	 */
	public static boolean deleteAccount(XMPPConnection connection)
	{
		try
		{
			AccountManager.getInstance(connection).deleteAccount();

			return true;
		}
		catch (Exception e)
		{
			return false;
		}
	}

	/**
	 * 删除修改密码
	 *
	 * @param connection
	 * @return
	 */
	public static boolean changePassword(XMPPConnection connection, String pwd)
	{
		try
		{
			AccountManager.getInstance(connection).changePassword(pwd);

			return true;
		}
		catch (Exception e)
		{
			return false;
		}
	}

	/**
	 * 好友追加
	 * @param connection
	 * @param firendUserName
	 * @param nickName
	 * @return
	 */
	public static boolean addFirend(XMPPConnection connection, String firendUserName, String nickName)
	{
		try
		{
			Roster roster = connection.getRoster();
			roster.createEntry(firendUserName, nickName,  new String[]{"Firends"});
			return true;
		}
		catch(Exception e)
		{
			return false;
		}
	}

	/**
	 * vcard情报编辑
	 * @param connection
	 * @param nickName
	 * @param email
	 * @param userIconPath
	 * @param desc
	 * @return
	 */
	public static boolean saveUserVcard(XMPPConnection connection, String nickName, String email, String userIconPath, String desc)
	{
		try
		{
			VCard vCard = new VCard();
			vCard.load(connection);
			vCard.setEmailHome("email");
			//vCard.setOrganization("售后");
			vCard.setNickName(nickName);

			//vCard.setField("sex", "男");
			//vCard.setPhoneWork("PHONE", "3443233");
			vCard.setField("TITLE", desc);
			File userIconFile = new File(userIconPath);
			if (userIconFile.exists())
			{
				vCard.setAvatar(getFileBytes(userIconFile));
			}


			vCard.save(connection);
		}
		catch (Exception e)
		{
			return false;
		}
		return true;
	}

	private static byte[] getFileBytes(File file) throws IOException {
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            int bytes = (int) file.length();
            byte[] buffer = new byte[bytes];
            int readBytes = bis.read(buffer);
            if (readBytes != buffer.length) {
                throw new IOException("Entire file not read");
            }
            return buffer;
        }
        finally {
            if (bis != null) {
                bis.close();
            }
        }
    }
}
